package com.example.exam.service;

import com.example.exam.exception.ServiceException;
import com.example.exam.mapper.UserMapper;
import com.example.exam.mapper.UserRoleMapper;
import com.example.exam.pojo.User;
import com.example.exam.pojo.UserRole;
import com.example.exam.service.imp.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class MyUserService implements UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insertUser(User user) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        int i = userMapper.insertUser(user);
        if(i==0){
            throw  new ServiceException("用户添加失败");
        }
        UserRole userRole=new UserRole();
        userRole.setRole(user.getId());
        userRole.setRole(0);
        int i1 = userRoleMapper.insertUserRole(userRole);
        if(i1==0){
            throw  new ServiceException("用户添加失败");
        }
    }

    @Override
    public void updateUserById(User user) {
        int i= userMapper.updateUserById(user);
        if(i==0){
            throw  new ServiceException("用户更新失败");
        }
    }

    @Override
    public User selectUserById(Long id) {

        return userMapper.selectUserById(id);
    }

    @Override
    public User selectUserByUsername(String username) {
        return  userMapper.selectUserByUsername(username);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteUserById(Long id) {
        int i = userMapper.deleteUserById(id);
        if(i==0){
            throw  new ServiceException("用户删除失败");
        }
        int i1 = userRoleMapper.deleteUserRoleByUserId(id);
        if(i1==0){
            throw  new ServiceException("用户删除失败");
        }
    }
}
